package com.skycity.auth.security.userdetails;

import cn.skycity.framework.core.model.Result;
import cn.skycity.framework.core.model.ResultCode;
import com.skycity.framework.uaa.api.UserFeignClient;
import com.skycity.framework.uaa.pojo.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserFeignClient userFeignClient;

    @Override
    public SysUserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Result<SysUser> result = userFeignClient.getUserByUsername(username);
        SysUserDetails userDetails = null;
        if (result.isSuccess()) {
            SysUser user = result.getData();
            if (null != user) {
//                user.setRoles(List.of("admin"));
                userDetails = new SysUserDetails(user);
            } else {
                throw new UsernameNotFoundException(ResultCode.USER_NOT_EXIST.getMsg());
            }
        }
        assert userDetails != null;
        if (!userDetails.isEnabled()) {
            throw new DisabledException(ResultCode.USER_ACCOUNT_LOCKED.name());
        } else if (!userDetails.isAccountNonLocked()) {
            throw new LockedException(ResultCode.USER_ACCOUNT_LOCKED.getMsg());
        } else if (!userDetails.isAccountNonExpired()) {
            throw new AccountExpiredException(ResultCode.USER_ACCOUNT_INVALID.getMsg());
        }
        return userDetails;
    }

}
